<template>
  <basic-dialog :visible="showExcel"
                title="导出EXCEL"
                min-width="1000px"
                is-show-basic-footer
                @close="$emit('close')"
                @submit="submitDateExcel"
  >
    <div >
<!--      <select-input ref="selectInput"-->
<!--                    class="padding-20"-->
<!--                    :list="searchCondition"-->
<!--                    @search="inputSearch"-->
<!--                    @clearSearchVal="clearSearchVal" />-->
      <div class="flex margin-t-20">
        <div style="width: 800px">
          <div class="title margin-r-20 margin-l-20 padding-l-20">人员绩效列表</div>
          <q-table :data="tableData"
                   :columns="columnsFilter"
                   style="height: 430px"
                   row-key="operatorId"
                   class="myTable scroll"
                   :loading="isTableLoading"
                   :pagination.sync="pagination"
                   :hide-bottom="!!tableData.length"
                   selection="multiple"
                   :selected.sync="selectedProduct"
                   color="primary">
          </q-table>
          <yz-pagination v-model="pagination" @onSearch="getList"/>
        </div>
        <div>
          <div class="title padding-l-20">已选项</div>
          <div class="select-box scrollbar">
            <div v-for="item in selectedProduct" :key="item.id">{{item.name}}</div>
          </div>
        </div>
      </div>
    </div>
  </basic-dialog>
</template>

<script>
// import SelectInput from 'src/components/select-input'
import { getPerformanceReports, downloadPerformanceDetail } from 'src/boot/statistics/performance'
import { mapGetters } from 'vuex'

export default {
  name: 'downloadPeopleDefine',
  components: {
    // SelectInput
  },
  props: {
    showExcel: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default: () => []
    },
    excelParams: {
      type: Object,
      default: () => {}
    },
    searchCondition: {
      type: Array,
      default: () => []
    },
    productTypeOptions: {
      type: Array,
      default: () => []
    },
    productStatusOptions: {
      type: Array,
      default: () => []
    },
    productPropertiesOptions: {
      type: Array,
      default: () => []
    },
    measureUnitOptions: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ]),
    columnsFilter () {
      return this.columns.filter(item => item.name !== 'operate')
    }
  },
  data () {
    return {
      tableData: [],
      excelHead: [
        {
          'field': 'operatorName',
          'name': '员工姓名'
        },
        {
          'field': 'date',
          'name': '日期'
        },
        {
          'field': 'shiftName',
          'name': '班制'
        },
        {
          'field': 'device',
          'name': '加工设备'
        },
        {
          'field': 'orderNumber',
          'name': '订单号'
        },
        {
          'field': 'workOrderId',
          'name': '工单号'
        },
        {
          'field': 'product',
          'name': '加工产品'
        },
        {
          'field': 'process',
          'name': '工序'
        },
        {
          'field': 'plannedQuantity',
          'name': '计划数量'
        },
        {
          'field': 'finishedQuantity',
          'name': '完工数量'
        },
        {
          'field': 'pieceUnitPrice',
          'name': '工序单价(计件)'
        },
        {
          'field': 'pieceRateWage',
          'name': '计件工资'
        },
        {
          'field': 'plannedDuration',
          'name': '计划工时'
        },
        {
          'field': 'actualDuration',
          'name': '实际工时'
        },
        {
          'field': 'timeUnitPrice',
          'name': '工序单价(计时)'
        },
        {
          'field': 'timeWage',
          'name': '计时工资'
        }, {
          'field': 'restDuration',
          'name': '休息时长(分钟)'
        }
      ],
      selectedProduct: [], // 选中的产品id
      isTableLoading: false,
      queryParams: {
      },
      // 表格分页配置
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      requestId: ''
    }
  },
  watch: {
    showExcel (val) {
      if (val) {
        Object.assign(this.queryParams, this.excelParams)
        Object.assign(this.pagination, this.$options.data.call(this).pagination)
        this.tableData = []
        this.selectedProduct = []
        this.getList()
      }
    }
  },
  methods: {
    // 清空搜索值
    clearSearchVal () {
      this.queryParams.keyword = ''
      this.queryParams.searchBy = ''
      this.pagination.pageNum = 1
      this.getList()
    },
    inputSearch (item, searchVal) {
      this.queryParams.keyword = searchVal
      this.queryParams.searchBy = item.id
      this.pagination.pageNum = 1
      this.getList()
    },
    // 获取列表数据
    getList () {
      this.isTableLoading = true
      getPerformanceReports({
        ...this.queryParams,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize
      })
        .then(res => {
          this.pagination.rowsNumber = res.data.total
          this.tableData = res.data.list
        }).finally(() => {
          this.isTableLoading = false
        })
    },
    submitDateExcel () {
      const data = {}
      const operatorIds = this.selectedProduct.map(item => item.operatorId)
      if (operatorIds.length === 0) {
        this.$message.warning('请选择导出列表')
        return
      }
      if (operatorIds.length > 200) {
        this.$message.warning('最多导出200条数据')
        return
      }
      data.operatorIds = operatorIds
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      data['before'] = this.queryParams.before
      data['since'] = this.queryParams.since
      data['excelHead'] = this.excelHead
      this.$q.loading.show()
      this.onSubscribe()
      downloadPerformanceDetail(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        } else if (this.queryParams.dateType === 'date') {
          this.showExcel = false
        }
      }).catch(() => {
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `人员绩效列表.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
      this.$emit('close')
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    }
  }
}
</script>

<style scoped lang="scss">
.select-box{
  height: 492px;
  width: 180px;
  overflow-x: hidden;
  border: 1px solid #d3d3d3;
  overflow-y: auto;
  border-radius: 0 0 5px 5px;
  padding: 10px 20px;
  line-height: 2;
}

.title{
  width: calc(100%-40px);
  background-color: #5f77fd;
  line-height: 2;
  border-radius: 5px 5px 0 0;
  color: #ffffff;
}
</style>
